package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.PageObject;
import com.cy.pj.sys.dao.SysLogDao;
import com.cy.pj.sys.entity.SysLog;
import com.cy.pj.sys.service.SysLogService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysLogServiceImpl implements SysLogService {
    @Autowired
    private SysLogDao sysLogDao;

    @Override
    public PageObject<SysLog> findPageObjects(String username, Integer pageCurrent) {
        // 1、参数验证
        if(pageCurrent == null || pageCurrent < 1)
            throw new IllegalArgumentException("当前页码值无效");
        // 2、分页获取数据
        int pageSize = 10;
        Page<SysLog> page = PageHelper.startPage(pageCurrent, pageSize);// 分页
        List<SysLog> records = sysLogDao.findPageObjects(username);
        // 3、返回数据
        return new PageObject<>((int)page.getTotal(), pageSize, pageCurrent, records);
    }

    @Override
    public int deleteObjectByIds(Integer[] ids) {
        // 1、参数校验
        if(ids == null || ids.length == 0)
            throw new IllegalArgumentException("请先选择");
        // 2、执行删除
        int rows = sysLogDao.deleteObjectByIds(ids);
        if(rows == 0)
            throw new ServiceException("记录可能已经不存在");
        // 3、返回数据
        return rows;
    }

    // @Async描述的方法为一个切入点方法，此方法会运行在一个新的线程中
    @Async // 此注解描述的方法会运行在springboot提供线程池中的一个线程上
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)// 描述的方法运行在独立的事务中
    public void saveObject(SysLog entity) {
        if(entity == null)
            throw new IllegalArgumentException("日志信息不能为空");
        String name = Thread.currentThread().getName();
        System.out.println("SysLogServiceImpl.saveObject.Thread = " + name);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sysLogDao.insertObject(entity);
    }
}
